package com.gict.antifraudback.interceptor;


import cn.hutool.core.util.StrUtil;
import com.gict.antifraudback.entity.User;
import com.gict.antifraudback.exception.MyException;
import com.gict.antifraudback.result.ResultEnum;
import com.gict.antifraudback.service.UserService;
import com.gict.antifraudback.utils.NoAuthorization;
import com.gict.antifraudback.utils.UserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 后台登录拦截器
 * @author 18239
 */
@Component
public class BackTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //将user放入threadLocal
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        if (((HandlerMethod) handler).hasMethodAnnotation(NoAuthorization.class)) {
            return true;
        }

        String token = request.getHeader("accessToken");

        if (StrUtil.isNotEmpty(token)) {
            // fixme 修改登录逻辑
            User user = this.userService.backQueryUserByToken(token);
            // 判断只允许超级管理员登录后台
            if (!"[\"admin\"]".equals(user.getRoles())){
                throw new MyException(ResultEnum.CODE_403);
            }
            if (null != user) {
                UserThreadLocal.set(user);
                return true;
            }
        }
        response.setStatus(401);
        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //从threadLocal中移除user
        UserThreadLocal.remove();

    }
}
